package com.example.bootkafka1.common;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableKafka
public class KafkaProducerConfig {

    @Value("${kafka.producer.bootstrapServers}")
    private String bootstrapServers;
    @Value("${kafka.producer.retries}")
    private String retries;
    @Value("${kafka.producer.batchSize}")
    private String batchSize;
    @Value("${kafka.producer.lingerMs}")
    private String lingerMs;
    @Value("${kafka.producer.bufferMemory}")
    private String bufferMemory;



    @Bean
    public ProducerFactory<Object,Object> producerFactory(){
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public Map<String,Object> producerConfigs(){
        Map<String,Object> propsMap = new HashMap<>();
        propsMap.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,bootstrapServers);
        propsMap.put(ProducerConfig.RETRIES_CONFIG,retries);
        propsMap.put(ProducerConfig.BATCH_SIZE_CONFIG,batchSize);
        propsMap.put(ProducerConfig.LINGER_MS_CONFIG,lingerMs);
        propsMap.put(ProducerConfig.BUFFER_MEMORY_CONFIG,bufferMemory);
        propsMap.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        propsMap.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class);
        return propsMap;
    }



    @Bean
    public KafkaTemplate<Object,Object> kafkaTemplate(){
        return new KafkaTemplate<Object,Object>(producerFactory(),true);
    }

}
